package scc.project.web.controller.manage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import scc.project.entity.Goods;
import scc.project.entity.vo.JsonVo;
import scc.project.entity.vo.RestFulPageVo;
import scc.project.service.GoodsService;

import javax.servlet.http.HttpSession;

/**
 * 商品管理控制器
 *
 * @author 陈圳佳
 *         日期：2015/6/22
 */
@Controller
@RequestMapping("/manage/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @RequestMapping(value = "/edit.html", method = RequestMethod.GET)
    public String edit() {
        return "/manage/shop/edit";
    }

    @RequestMapping(value = "/edit/{id}.html", method = RequestMethod.GET)
    public String edit(@PathVariable("id") Long id, ModelMap modelMap) {
        Goods goods = goodsService.get(id);
        modelMap.addAttribute("goods", goods);
        modelMap.addAttribute("action", "");
        return "/manage/shop/edit";
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public JsonVo update(@PathVariable("id") Long id) {
//        Goods goods = goodsService.get(id);
//        modelMap.addAttribute("goods", goods);
//        modelMap.addAttribute("action", "");
//        return "/manage/shop/edit";
        JsonVo jsonVo = new JsonVo();
        return jsonVo;
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public JsonVo get(@PathVariable("id") Long id, HttpSession session) {
        Goods goods = goodsService.get(id);
        return new JsonVo().addValue("goods", goods);
    }

    @RequestMapping(value = "/list/{page}.html", method = RequestMethod.GET)
    public String list(@PathVariable("page") Integer page,
                       @RequestParam(value = "shopName", required = false) String shopName,
                       @RequestParam(value = "origin", required = false) String origin,
                       ModelMap modelMap) {

        try {
            RestFulPageVo<Goods> pageVo = RestFulPageVo.convert(goodsService.find(page, shopName, origin), ".html");
            pageVo.addProperty("data-pjax", "#content");
            modelMap.addAttribute("pageVo", pageVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/manage/shop/list";
    }

    @ResponseBody
    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public Goods getByName(@RequestParam(value = "name") String name) throws Exception {
        return goodsService.getByName(name);
    }
}
